package com.guoxue.dao.impl;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.guoxue.dao.IPlanProgressDao;
import com.guoxue.domain.PlanProgressVo;

@Repository
public class PlanProgressDaoImpl extends BaseDaoImpl<PlanProgressVo> implements IPlanProgressDao {

	@Override
	public List<PlanProgressVo> getUserPlans(int id) {
		return find("From PlanProgress p WHERE p.uid=?", new Object[] { id });
	}

	@Override
	public PlanProgressVo getPlanByUserAndPlanId(int id, int planId) {
		return get("From PlanProgressVo p WHERE p.uid=? AND p.currentPlanId=?", new Object[] { id, planId });
	}

	@Override
	public void savePlan(PlanProgressVo plan) {
		saveOrUpdate(plan);
	}

	@Override
	public List<PlanProgressVo> getUserPlansByPlanId(int id, int beginPlanId, int endPlanId) {
		return find("From PlanProgressVo p WHERE p.uid=? AND p.currentPlanId >=? AND p.currentPlanId<=?",
				new Object[] { id, beginPlanId, endPlanId });
	}

	@Override
	public int getReadersCount(int id, int begin, int end) {
		Long o = count("SELECT count(p.id) From PlanProgressVo p WHERE p.uid=? AND p.currentPlanId >=? AND p.currentPlanId<=? AND p.medal=0",new Object[] { id, begin, end });
		int c = 0;
		if (o!=null){
			c = o.intValue();
		} 
		return c;
	}

	@Override
	public PlanProgressVo getUserPlanByUidAndPlanId(int id, int planId) {
		return get("From PlanProgressVo p WHERE p.uid=? AND p.currentPlanId=?",new Object[] { id,planId});
	}

	@Override
	public long getCount(int planId) {
		return count("SELECT count(p.id) From PlanProgressVo p WHERE p.currentPlanId=?",new Object[] {planId});
	}

	@Override
	public long getCompleteCount(int currentReadRound, int planId) {
		long o = count("SELECT count(p.id) From PlanProgressVo p WHERE p.currentReadRound>=? AND p.currentPlanId=?",new Object[] { currentReadRound,planId});
		return o;
	}
 
	@Override
	public PlanProgressVo getLastCommit(int id) {
		List<PlanProgressVo> ls = find("FROM PlanProgressVo p WHERE p.uid=? ORDER BY p.commitDate DESC", new Object[] {id}, 0, 1);
		if (ls.size()<1){
			return null;
		} else {
			return  ls.get(0);
		}
		
	}

}
